#!/bin/sh
export PYTHONPATH=/app

echo "Waiting for database to be ready..."
until psql "$DATABASE_URL" -c "select 1" 2>/dev/null; do
    echo "Database is unavailable - sleeping"
    sleep 1
done
echo "Database is up!"

echo "Running database migrations..."
mkdir -p /app/vul_app/migrations
touch /app/vul_app/migrations/__init__.py
# 2. 检查是否需要生成初始迁移
if [ ! -f /app/vul_app/migrations/0001_initial.py ]; then
    echo "Generating initial migrations..."
    python manage.py makemigrations
fi

python manage.py migrate
echo "Checking for test data..."
python /app/populate_test_data.py

if [ "$DEBUG" = "1" ]; then
    echo "Starting Django in debug mode with debugpy..."
    python -m debugpy --listen 0.0.0.0:5678 --wait-for-client manage.py runserver 0.0.0.0:8000
else
    echo "Starting Django in production mode..."
    python manage.py runserver 0.0.0.0:8000
fi